package org.apache.lucene.index.tag;

import java.io.IOException;

import org.apache.lucene.index.tag.TagIndex.TagTerm;
import org.apache.lucene.store.IndexInput;
import org.apache.lucene.util.UnicodeUtil;

public class TagTermBuffer {
  private UnicodeUtil.UTF16Result text = new UnicodeUtil.UTF16Result();
  private UnicodeUtil.UTF8Result bytes = new UnicodeUtil.UTF8Result();
  public int fieldNumber;

  public final void set(TagTerm tagTerm) {
    if (tagTerm == null) {
      reset();
      return;
    }
    final String termText = tagTerm.text;
    final int termLen = termText.length();
    text.setLength(termLen);
    termText.getChars(0, termLen, text.result, 0);
    fieldNumber = tagTerm.fieldNumber;
  }

  public final void set(TagTermBuffer other) {
    text.copyText(other.text);
    fieldNumber = other.fieldNumber;
  }

  public final void read(IndexInput input) throws IOException {
    fieldNumber = input.readVInt();
    int length = input.readVInt();
    bytes.setLength(length);
    input.readBytes(bytes.result, 0, length);
    UnicodeUtil.UTF8toUTF16(bytes.result, 0, length, text);
  }

  private static final int compareChars(char[] chars1, int len1, char[] chars2, int len2) {
    final int end = len1 < len2 ? len1 : len2;
    for (int k = 0; k < end; k++) {
      char c1 = chars1[k];
      char c2 = chars2[k];
      if (c1 != c2) {
        return c1 - c2;
      }
    }
    return len1 - len2;
  }

  public final int compareTo(TagTermBuffer other) {
    if (fieldNumber == other.fieldNumber) 
      return compareChars(text.result, text.length, other.text.result, other.text.length);
    else
      return TagIndex.compareInt(fieldNumber, fieldNumber);
  }
  
  public String getText() {
    return new String(text.result, 0, text.length);
  }

  public void reset() {
    fieldNumber = -1;
    text.setLength(0);
  }
}
